#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
autor: joão pedro brites raposo alexandre
data criação: 2011/11/24
linguagem: python
modulo: beautifulsoup
versão: v1.0
'''


import time
import urllib2
from BeautifulSoup import BeautifulSoup
from file_plot import Plot
from file_csv import Csv


#class to operate width html files
class Soup:

    #class contructor
    def __init__(self):
        pass

    #-----------------------------------------------------------------
    #metodo para contar html tags de páginas web 
    #-----------------------------------------------------------------    
    def count_tags_from_http_address(self, http_address):
        
##        try:
        print 'consultar (total de html tags width beautifulSoup soup)...'
        t1 = time.clock()
        page = urllib2.urlopen(http_address)

        soup = BeautifulSoup(page)

        #target search
        target_search1 = ['h1','h2','h3','div','p','ul','ol','img']
        target_search2 = ['H1','H2','H3','DIV','P','UL','OL','IMG']
        
        data = []

        #search in soup where target_search exists
        for i in range(len(target_search1)):
            #print 'searching {0}'.format(target_search2[i])
            count = 0
            for elem in soup(target_search1[i] or target_search2[i]):
                count += 1
                pass
            #print count
            data.append(count)
            pass

        #print data
        t2 = time.clock()

        print 'temp =', t2-t1
        print 'consulta ok.'

        obj1 = Csv()
        obj1.create_file_html_tag('statistics_html_tags_from_web.csv',target_search2, data)

        obj2 = Plot()
        obj2.create_plot_file_html_search(data, target_search2)
##        except:
##            print u'erro de conexão ou url type desconhecido', http_address
##        pass


    #----------------------------------------------------------
    #CHAMADA DE FUNÇÃO
    #A função funciona ok. Erro apenas quado invocadas pelo main
    
    #http_address = 'http://www.google.pt'
    #count_tags_from_http_address(http_address)


